package com.kds.changzhou.netty;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.json.JSONUtil;
import com.kds.changzhou.dao.ConfigDao;
import com.kds.changzhou.data.Gateway;
import com.kds.changzhou.handler.HandlerConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author 孔德嵩
 */
@Component
@Slf4j
public class TcpClientStartLisener implements ApplicationRunner {


    @Autowired
    private ConfigDao configDao;


    @Autowired
    private HandlerConfig handlerConfig;

    @Override
    public void run(ApplicationArguments args) throws Exception {

        List<Gateway> gateways = configDao.queryGateways();

        log.debug("配置的全部采集器信息：\n{}", JSONUtil.toJsonStr(gateways));


        /**
         * 每个Gateway启动一个客户端连接
         */
        for (Gateway gateway : gateways) {

            TcpClient tcpClient = handlerConfig.createTcpClient(gateway);

            tcpClient.start();

            ThreadUtil.sleep(200);
        }
        log.info("\u001B[33m共{}个采集器已启动\u001B[0m", gateways.size());

    }
}
